package parsers;

import database.UserData;
import entity.Client;
import entity.UserConnectData;
import logger.LoggerManager;
import resurses.LoggerMessage;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

/**
 * Created by alexander.makalov on 23.10.2014.
 */
public class UserDataParser implements IParser{

    private final static String configFileName = "hibernate.cfg.xml";

    @Override
    public void startParsing() {
        try {
            LoggerManager.getLogger().Log(String.format(LoggerMessage.START_XML_PARSING,configFileName), LoggerManager.LogLevel.INFO);
            FileReader reader = new FileReader(configFileName);
            JAXBContext jaxbContext = JAXBContext.newInstance(UserConnectData.class);
            LoggerManager.getLogger().Log(LoggerMessage.START_PARSING_FILE, LoggerManager.LogLevel.INFO);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            UserConnectData userConnectData = (UserConnectData) jaxbUnmarshaller.unmarshal(reader);
            LoggerManager.getLogger().Log(LoggerMessage.END_PARSING_FILE, LoggerManager.LogLevel.INFO);
            getUserData(userConnectData.getSsFactoryItem().sessionFactoryItems());
            UserData.checkData();
        } catch (FileNotFoundException|JAXBException e) {
            LoggerManager.getLogger().Log(e.getMessage(), LoggerManager.LogLevel.ERROR);
            //e.printStackTrace();
        }
    }

    private void getUserData(List<UserConnectData.SessionFactoryItem> sessionFactoryItems){
        for (UserConnectData.SessionFactoryItem item : sessionFactoryItems){
            if ("hibernate.connection.url".equals(item.getAttrbuteSring())) UserData.setDbUrl(item.getValueString());
            if ("hibernate.connection.username".equals(item.getAttrbuteSring())) UserData.setUserName(item.getValueString());
            if ("hibernate.connection.password".equals(item.getAttrbuteSring())) UserData.setUserPass(item.getValueString());
        }
    }

    @Override
    public List<Client> getClientsList() {
        return null;
    }
}
